<?php

class ServerController extends Controller {

	public function IndexAction() {
			print "fds";
	}
	
	public function ImportAction()
	{
		include PATH_SERVER_APP . '..' . DS . 'modules' . DS . 'ImportXML.php';
		
		$sql = 'SELECT * FROM shop WHERE active = 1 AND import_url IS NOT NULL ORDER BY last_import';
		$res = $db->prepare($sql)->execute()->FetchAllAssoc();
		foreach($res as $shop)
		{
		
			$content = file_get_contents($shop['import_url']);
			try {
				ImportXML::instance($shop['id_shop'])->parseXml($content);
			} catch (Exception $e)
			{

			}
		}
		$update = sprintf('UPDATE shop SET last_import = \'%s\' WHERE id_shop = %d', $now, $line['id_shop']);
		$db->prepare($sql)->execute();		
		
	}
	
	public function ManufacturerCounterAction()
	{
		$db = Registry::Get('db');
		$sql = "TRUNCATE TABLE manufacturer_category";
		$db->prepare($sql)->execute();
		
		$sql = "INSERT INTO manufacturer_category (id_manufacturer, id_category, count) SELECT product.id_manufacturer, category.parent as id_category, count(product.id_product) as count FROM product LEFT JOIN category ON (product.id_category = category.id_category) WHERE category.active = 1 AND product.active = 1 AND product.id_product IN (SELECT id_product FROM property_value WHERE parent IS NOT NULL) GROUP BY product.id_manufacturer, category.parent";
		$db->prepare($sql)->execute();
	}
	
	
	public function PopularityRankingAction() {
		
		$db = Registry::Get('db');
		$sql = "select max(subcount) as count, id_category from (SELECT count(id_comments) as subcount, id_category FROM `comments` as c1 join product p1 on (c1.type = '1' and c1.id_content=p1.id_product) group by p1.id_product) as a1";
		$stmt = $db->prepare($sql)->execute();
		
		$result = $stmt->FetchAllAssoc();
		
		$categoryCountOverall = array();
		foreach($result as $row) {
			$categoryCountOverall[$row['id_category']] = $row['count'];
		}
		
		$sql = "SELECT count(id_comments) as count, id_product, id_category FROM `comments` join product on (comments.type = '1' and comments.id_content=product.id_product) group by id_product";
		$stmt = $db->prepare($sql)->execute();
		
		$result = $stmt->FetchAllAssoc();
		
		foreach($result as $row) {
			
			$rank = round(($row['count']/$categoryCountOverall[$row['id_category']])*100);
			echo $rank.'<br />';
			$sql = "replace into product_ranking set id_product_ranking=(select x.id_product_ranking from product_ranking as x where x.id_category=".$row['id_category']." and x.id_product=".$row['id_product']." and x.type=3 limit 1), rate=$rank, type=3, id_category=".$row['id_category'].", id_product=".$row['id_product'];
			$db->execute($sql);
			$sql ="update product set popularity='".$rank."' where id_product = ".$row['id_product'];
			$db->execute($sql);
		}
		
	}
	
	public function RankingPointsAction() {
		
		$db = Registry::Get('db');
		$sql = "select sum(product_votes.rate) as rate_sum, count(product_votes.id_product) as count, product.id_product, id_category FROM product_votes join product on (product_votes.id_product=product.id_product) group by product_votes.id_product";
		$stmt = $db->prepare($sql)->execute();
		
		$result = $stmt->FetchAllAssoc();
		
		
		foreach($result as $row) {

			$rank = ($row['rate_sum']/$row['count']);
			echo $rank.'<br />';
			$sql = "replace into product_votes_ranking set id_product_votes_ranking=(select x.id_product_votes_ranking from product_votes_ranking as x where x.id_product=".$row['id_product']." and x.id_product_votes_type=1 limit 1), value=$rank, id_product_votes_type=1, id_product=".$row['id_product'];
			$db->execute($sql);
			$sql ="update product set rate='".$rank."' where id_product = ".$row['id_product'];
			$db->execute($sql);
		}
		
	}
	
	public function GeneralRankAction() {
		$db = Registry::Get('db');
		$sql = "select id_product, rate, popularity, id_category FROM product where active=1 and rank!='0' order by id_category ASC,rate DESC, popularity ASC";
		$stmt = $db->prepare($sql)->execute();
		
		$result = $stmt->FetchAllAssoc();
		

		$rank = 0;
		$cat = 0;
		foreach($result as $row) {
			if($cat!=$row['id_category']) {
				$rank = 0;
			}
			$rank++;
			echo $row['id_product'].':'.$rank.'<br />';
			//$sql = "replace into product_votes_ranking set id_product_votes_ranking=(select x.id_product_votes_ranking from product_votes_ranking as x where x.id_product=".$row['id_product']." and x.id_product_votes_type=1 limit 1), value=$rank, id_product_votes_type=1, id_product=".$row['id_product'];
			//$db->execute($sql);
			$sql ="update product set rank='".$rank."' where id_product = ".$row['id_product'];
			echo $sql.'<br>';
			$db->execute($sql);
			$cat = $row['id_category'];
		}
	}
	

	public function GenerateModelAction($param) {

		echo "Generating model... <br>";

		require_once('../core/lib/Smarty/Smarty.class.php');
		$smarty = new Smarty();
		$smarty->template_dir = Config::Get('PATH_SMARTY_MODEL_TEMPLATE');
		$smarty->compile_dir = Config::Get('PATH_SMARTY_MODEL_COMPILE');
//echo PATH_SMARTY_MODEL_TEMPLATE;
		$db = Registry::Get('db');

		$sql = " select table_name from information_schema.tables where table_schema <> 'information_schema' ";
		$stmt = $db->prepare($sql)
						->execute($sql);

		$tables = $stmt->FetchAllRow();
		foreach ($tables as $table) {

			$tableName = $table[0];
			$className = ucfirst(Utils::SQLName2PHPName($tableName));

			$smarty->assign('tableName', $tableName);
			$smarty->assign('className', $className);
//var_dump($smarty);
			// zależne obiekty/tabele działa dopiero od mySQL 5.1.16
//			$sql = " select table_name from referential_constraints where constraint_schema <> 'information_schema' and referenced_table_name = '$tableName' ";
//			$stmt = $db->prepare($sql)
//			->execute($sql);
//
//			$refTableNames = array();
//
//			$refTables = $stmt->FetchAllRow();
//			foreach ($refTables as $refTable) {
//				$tmp_name = Utils::SQLName2PHPName($refTable[0]);
//				$refTables[$refTable[0]] = $tmp_name;
//			}
//
//			$smarty->assign('refTables', $refTables);
			// kolumny tabeli dla obiektu

			$sql = " select column_name from information_schema.columns where table_name='$tableName'; ";
			$stmt = $db->prepare($sql)
							->execute($sql);

			$columnNames = array();

			$columns = $stmt->FetchAllRow();
			foreach ($columns as $column) {
				if ($column[0] === 'id_' . $tableName) {
					$tmp_name = 'id';
				} else {
					$tmp_name = Utils::SQLName2PHPName($column[0]);
				}
				$columnNames[$column[0]] = $tmp_name;
			}


			$smarty->assign('columnNames', $columnNames);
			$output = '<?php' . $smarty->fetch('templateModel.tpl') . '?>';
			$file = fopen(PATH_MODEL_TMP . $className . '.class.php', "w");
			$bytes = fwrite($file, $output);
			fclose($file);

			echo "Class - " . $className . '.class.php' . " - $bytes bytes written<br>";

			$outputDAL = '<?php' . $smarty->fetch('templateModelDAL.tpl') . '?>';
			$file = fopen(PATH_MODEL_TMP . $className . 'DAL.class.php', "w");
			$bytes = fwrite($file, $outputDAL);
			fclose($file);

			echo "DAL - " . $className . 'DAL.class.php' . " - $bytes bytes written<br>";
		}

		echo "Done... <br>";
	}

	public function SchedulerAction($param) {
		$arrayScheduler = SchedulerDAL::GetArrayToCron();
		foreach ($arrayScheduler as $objScheduler) {
			$paramScheduler = $objScheduler->getParam();
			// wywolujemy crony
			$mfCurl = new MfCurl();
			$mfCurl->SetUserName('elance');
			$mfCurl->SetPassword('goldenline');
			$curlExec = $mfCurl->Get("http://server.getak.pl/index.php?controller=" . $objScheduler->getController() . "&action=" . $objScheduler->getAction());
			if ($curlExec == false) {
				MFLog::Error(" cron się nie wykonał funkcja:  " . Router::GenerateUrl(array($objScheduler->getController() => $objScheduler->getAction())), 0, 0, __FILE__, __METHOD__);
			}
			else
				var_dump($curlExec);

			$objScheduler->SetDate(Utils::GetNowDate());
			$dalObj = CommisionCommentDAL::GetDalDataObj();
			$dalObj->setObj($objScheduler);
			SchedulerDAL::Update($dalObj);
		}
	}

	public function PremiumusersAction($param)
	{
		
	}
	
	public function BadgesAction($param) {
		Registry::Get('db')->BeginTransaction();
		Registry::Get('db')->prepare('TRUNCATE user_badge')->execute();
		Registry::Get('db')->prepare('UPDATE user SET badge_cache = ""')->execute();

		$sql = 'SELECT id_user, id_dict_actions, SUM(user_activity.points) AS points_gathered, p.id_user_activity_badges AS id_badge, p.points AS points, p.image AS image, p.badge AS badge, if(p.group IS NULL, p.id_user_activity_badges, p.group) AS `group` FROM user_activity LEFT JOIN user_activity_badges p USING(id_dict_actions) GROUP BY id_user, `group`, id_badge HAVING id_badge IS NOT NULL ORDER BY `group` ASC, points DESC';

		$list = Registry::Get('db')->prepare($sql)->execute()->FetchAllAssoc();

		$users = array();

		foreach($list AS $row) {
			if(is_null($row['group'])) {
				if($row['points_gathered'] >= $row['points'])$users[$row['id_user']]['badges'][] = array('id' => $row['id_badge'], 'name' => $row['badge'], 'image' => $row['image'], 'points' => $row['points'], 'pointsGathered' => $row['points_gathered']);
			}else{
				if($row['points_gathered'] >= $row['points']){
					if(!isset($users[$row['id_user']]['badges'][$row['group']]) || intval($users[$row['id_user']]['badges'][$row['group']]['points']) < intval($row['points']))$users[$row['id_user']]['badges'][$row['group']] = array('id' => $row['id_badge'], 'name' => $row['badge'], 'image' => $row['image'], 'points' => $row['points'], 'pointsGathered' => $row['points_gathered']);
				}
			}
		}

		//var_dump($list);

		$sql = array();

		foreach($users AS $id_user => $data) {

			foreach($data['badges'] AS $row) {
				$sql[] = 'INSERT INTO user_badge SET id_user = '.$id_user.', id_user_activity_badges = '.$row['id'];
			}

			$dejta = mysql_escape_string(serialize(array_values($data['badges'])));

			$sql[] = 'UPDATE user SET badge_cache = "'.$dejta.'" WHERE id_user = '.$id_user;

		}


		foreach($sql AS $line)
			Registry::Get('db')->prepare($line)->execute();



		Registry::Get('db')->CommitTransaction();
	}

	public function UserStatusAction($param) {
		Registry::Get('db')->BeginTransaction();
		Registry::Get('db')->prepare('UPDATE user SET is_expert = 0, is_vip = 0')->execute();
		$vip = (array)unserialize(array_shift(Config::Get('vip_threshold')));
		$expert = (array)unserialize(array_shift(Config::Get('expert_threshold')));


		$sql = 'SELECT a.id_user AS id_user, a.id_dict_actions AS id_dict_actions, SUM(a.points) AS points, b.premium AS premium FROM user_activity a LEFT JOIN user b USING(id_user) GROUP BY id_user, id_dict_actions ';

		$list = Registry::Get('db')->prepare($sql)->execute()->FetchAllAssoc();

		$users = array();
		foreach($list AS $row) {
			$users[$row['id_user']]['premium'] = $row['premium'];
			$users[$row['id_user']]['badges'][$row['id_dict_actions']] = $row['points'];
		}

		$vips = array(0);
		$experts = array(0);

		foreach($users as $id => $data) {

			$_expert = array_intersect_key($data['badges'], $expert);
			
			if(count($_expert) == count($expert)) {
				
				$good = true;
				foreach($_expert AS $k => $v) {
					if($v < $expert[$k])
						$good = false;
				}
				if($good)$experts[] = $id;
			}

			if($data['premium'] > 0) {
				$_vip = array_intersect_key($data['badges'], $vip);
				if(count($_vip) == count($vip)) {

					$good = true;
					foreach($_vip AS $k => $v) {
						if($v >= $vip[$k])
							$good = false;
					}
					if($good)$vips[] = $id;
				}
			}

		}

		$sql = 'UPDATE user SET is_expert = 1 WHERE id_user IN ('.implode(',',$experts).')';
		Registry::Get('db')->prepare($sql)->execute();
		$sql = 'UPDATE user SET is_vip = 1 WHERE id_user IN ('.implode(',',$vips).')';
		Registry::Get('db')->prepare($sql)->execute();

		Registry::Get('db')->CommitTransaction();
	}
}

?>